//
//  QuDouJifenController.m
//  quxiangtao
//
//  Created by HHuajiang on 2018/11/26.
//  Copyright © 2018 shanhaijin. All rights reserved.
//

#import "QuDouJifenController.h"
#import "HYSegmentControl.h"
#import "ChangingModel.h"
#import "ChangingViewCell.h"
#import "ChangepopView.h"

@interface QuDouJifenController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *recordTableView;
@property (nonatomic, strong) NSMutableArray *recordArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *selectIndex;
@end

@implementation QuDouJifenController

- (void)viewDidLoad {
    [super viewDidLoad];
    WS(weakSelf);
    
    self.page = 1;
    self.selectIndex = @"1";
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"兑换记录";
    NSMutableArray *titleSourcd = [NSMutableArray arrayWithObjects:@"积分兑换趣豆记录", @"趣豆兑换积分记录", nil];
    HYSegmentControl *segmentControl = [HYSegmentControl segmentColor:CGRectMake(0, 0, self.view.bounds.size.width, 44) titleSource:titleSourcd titleColor:Color333333 selectTitleColor:Color333333 titleFont:[UIFont systemFontOfSize:13] selectTiteFont:[UIFont fontWithName:@"Helvetica-Bold" size:13] backgroundColor:[UIColor whiteColor] bottomLingColor:[UIColor redColor]];
    [self.view addSubview:segmentControl];
    
    segmentControl.finished = ^(NSInteger btnTag) {
        weakSelf.page = 1;
        if (btnTag == 0) {
            weakSelf.selectIndex = @"1";
            [weakSelf loadViewWithDataType:@"1"];
        } else {
            [weakSelf loadViewWithDataType:@"2"];
            weakSelf.selectIndex = @"2";
        }
    };
    
    [self loadViewWithDataType:@"1"];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf loadViewWithDataType:weakSelf.selectIndex];
    }];
    [header beginRefreshing];
    [header setTitle:@"下拉可以刷新!" forState:MJRefreshStateIdle];
    [header setTitle:@"松手立即刷新!" forState:MJRefreshStatePulling];
    [header setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
    header.stateLabel.font = Font(24);
    header.backgroundColor = [UIColor clearColor];
    [header setTintColor:[UIColor clearColor]];
    header.stateLabel.textColor = Color999999;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.recordTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf loadViewWithDataType:weakSelf.selectIndex];
    }];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载。。。。" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据！" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = Font(17);
    footer.stateLabel.textColor = Color999999;
    self.recordTableView.mj_footer = footer;
    self.recordTableView.mj_footer.hidden = NO;
    
    [self.view addSubview:self.recordTableView];
    [self.recordTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(44);
    }];
}

- (NSMutableArray *)recordArray {
    if (!_recordArray) {
        _recordArray = [[NSMutableArray alloc] init];
    }
    return _recordArray;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return jisuan(140);
}

#pragma mark -delegate \ datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.recordArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WS(weakSelf);
    ChangingModel *model = self.recordArray[indexPath.row];
    if (model.status == 2) {
        return;
    }
    ChangepopView *popview = [[ChangepopView alloc] init];
    popview.model = model;
    [popview showPoPview];
    popview.sureClickBlock = ^(NSString * _Nonnull text) {
        [weakSelf submissionData:model.recordId Unit:text Index:indexPath.row];
    };
    NSString *par = [NSString stringWithFormat:@"{\"type\" : \"%@\", \"user_id\" : \"%@\", \"id\" : \"%@\"}", [RSA encryptString:self.selectIndex publicKey:PublicKey], [RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey],[RSA encryptString:model.recordId publicKey:PublicKey]];
    [PPNetworkHelper POST:@"transaction/Index/updatedetail" parameters:@{@"json":par} success:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 1) {
            popview.dicationary = responseObject[@"data"];
        } else {
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
    } failure:^(NSError *error) {
        [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
    }];
}


- (void)submissionData:(NSString *)Id Unit:(NSString *)unit Index:(NSInteger)index {
    
    WS(weakSelf);
    NSString *par = [NSString stringWithFormat:@"{\"type\" : \"%@\", \"user_id\" : \"%@\", \"id\" : \"%@\", \"unit\" : \"%@\"}", [RSA encryptString:self.selectIndex publicKey:PublicKey], [RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey],[RSA encryptString:Id publicKey:PublicKey],[RSA encryptString:unit publicKey:PublicKey]];
    [PPNetworkHelper POST:@"transaction/Index/updateaction" parameters:@{@"json":par} success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 1) {
            ChangingModel *model = [ChangingModel mj_objectWithKeyValues:responseObject[@"data"]];
            [weakSelf.recordArray replaceObjectAtIndex:index withObject:model];
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:index inSection:0];
            [weakSelf.recordTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            if (self.changeButtonClickBlock) {
                self.changeButtonClickBlock();
            }
        }
        [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
    } failure:^(NSError *error) {
        [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChangingViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChangingViewCell"];
    cell.model = self.recordArray[indexPath.row];
    return cell;
}


- (UITableView *)recordTableView {
    
    if (!_recordTableView) {
        _recordTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _recordTableView.delegate = self;
        _recordTableView.dataSource = self;
        _recordTableView.showsVerticalScrollIndicator = NO;
        _recordTableView.showsHorizontalScrollIndicator = NO;
        _recordTableView.estimatedRowHeight = 0;
        _recordTableView.estimatedSectionHeaderHeight = 0;
        _recordTableView.estimatedSectionFooterHeight = 0;
        _recordTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_recordTableView registerClass:[ChangingViewCell class] forCellReuseIdentifier:@"ChangingViewCell"];
        if (@available(iOS 11.0, *)) {
            _recordTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _recordTableView;
}


- (void)loadViewWithDataType:(NSString *)type {
    
    WS(weakSelf);
    NSString *str = [NSString stringWithFormat:@"{\"user_id\" : \"%@\", \"type\" : \"%@\", \"page\" : \"%@\",\"number\" : \"%@\"}", [RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey], [RSA encryptString:type publicKey:PublicKey], [RSA encryptString:[NSString stringWithFormat:@"%ld",(long)self.page] publicKey:PublicKey], [RSA encryptString:@"100" publicKey:PublicKey]];
    
    [PPNetworkHelper POST:@"transaction/Index/matching_record" parameters:@{@"json":str} success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue] == 1) {
            if (weakSelf.page == 1) {
                [weakSelf.recordArray removeAllObjects];
            }
            NSArray *array = responseObject[@"data"];
            for (NSDictionary *dic in array) {
                ChangingModel *model = [ChangingModel mj_objectWithKeyValues:dic];
                [weakSelf.recordArray addObject:model];
            }
            [weakSelf.recordTableView reloadData];
        } else {
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
        [weakSelf.recordTableView.mj_header endRefreshing];
        [weakSelf.recordTableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        [weakSelf.recordTableView.mj_header endRefreshing];
        [weakSelf.recordTableView.mj_footer endRefreshing];
        [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
    }];
}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    
}

@end
